<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="进度值" prop="progress">
        <el-input
          v-model="queryParams.progress"
          placeholder="请输入进度值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:progress:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:progress:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:progress:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:progress:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handlePrint"
          v-hasPermi="['project:progress:print']"
        >打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          @click="handleStatistic"
          v-hasPermi="['project:progress:statistic']"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="progressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" sortable/>
      <el-table-column label="项目ID" align="center" prop="projectId" sortable/>
      <!--<el-table-column label="进度值" align="center" prop="progress"/>-->
      <el-table-column label="进度" align="center">
        <template #default="{ row }">
          <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="row.progress"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:progress:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:progress:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['project:progress:view']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改progress对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="进度值" prop="progress">
          <el-input v-model="form.progress" placeholder="请输入进度值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看contract对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" :disabled="isViewMode" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="进度值" prop="progress">
          <el-input v-model="form.progress" :disabled="isViewMode" placeholder="请输入合同金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelView">返  回</el-button>
      </div>
    </el-dialog>

    <!-- 数据统计对话框 -->
    <el-dialog
      :title="'统计结果'"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleCloseDialog"
      append-to-body
    >
      <div id="echart-container" style="width: 80%; height: 400px;"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { listProgress, getProgress, delProgress, addProgress, updateProgress } from "@/api/project/progress";
  import * as echarts from "echarts";

  export default {
    name: "Progress",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // progress表格数据
        progressList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openView: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          projectId: null,
          progress: null
        },
        percentage: 0,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          projectId: [
            { required: true, message: "项目ID不能为空", trigger: "blur" }
          ],
          progress: [
            { required: true, message: "进度值不能为空", trigger: "blur" }
          ]
        },
        isViewMode: false,
        dialogVisible: false,
        chartData: {
          projectId: [],
          progress: []
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询progress列表 */
      getList() {
        this.loading = true;
        listProgress(this.queryParams).then(response => {
          this.progressList = response.rows;
          this.total = response.total;
          this.loading = false;
        });

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      cancelView() {
        this.openView = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          projectId: null,
          progress: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加progress";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getProgress(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改progress";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProgress(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addProgress(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除progress编号为"' + ids + '"的数据项？').then(function() {
          return delProgress(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('project/progress/export', {
          ...this.queryParams
        }, `progress_${new Date().getTime()}.xlsx`)
      },
      /** 查看按钮 **/
      handleView(row) {
        console.log("clicked view button");
        this.reset();
        const id = row.id || this.ids
        getProgress(id).then(response => {
          this.form = response.data;
          this.openView = true;
          this.title = "查看进度";
          this.isViewMode = true;
        });
      },
      /** 打印按钮操作 **/
      handlePrint() {
        // 获取表格的 DOM 元素
        const printContent = document.querySelector('.el-table');

        // 创建一个新的窗口来打印内容
        const newWindow = window.open('', '_blank');

        const tableHeader = printContent.querySelector('thead'); // 获取表头
        const tableRows = printContent.querySelectorAll('tbody tr'); // 获取所有行

        let printContentHTML = '<table border="1">'; // 创建一个新的表格开始标签

        //表头
        if (tableHeader) {
          // 获取表头的所有列
          const headerCells = tableHeader.querySelectorAll('th');
          let headerHTML = '<tr>';

          // 只保留指定的列
          const columnIndexes = [1, 2, 3]; // 例如：设备ID, 设备名称, 检查时间列索引
          columnIndexes.forEach(index => {
            if (headerCells[index]) {
              headerHTML += `<th>${headerCells[index].innerHTML}</th>`; // 获取指定列的表头并插入
            }
          });

          headerHTML += '</tr>';
          printContentHTML += headerHTML; // 将表头添加到打印内容中
        }

        // 遍历表格的每一行，提取指定列的数据
        tableRows.forEach((row, rowIndex) => {
          // 跳过表头行或其他无效行
          const cells = row.querySelectorAll('td'); // 获取每一行的所有单元格
          if (cells.length > 0) {
            // 只提取你需要的列，假设你需要第1列、2列和4列
            let rowHTML = '<tr>';
            // 指定需要的列索引（从0开始）
            const columnIndexes = [1, 2, 3];  // 例如：设备ID, 设备名称, 检查时间列索引
            columnIndexes.forEach(index => {
              if (cells[index]) {
                rowHTML += `<td>${cells[index].innerHTML}</td>`; // 获取指定列的数据并插入到新行
              }
            });
            rowHTML += '</tr>';
            printContentHTML += rowHTML; // 将处理过的行添加到打印内容中
          }
        });

        printContentHTML += '</table>'; // 结束表格标签

        // 打开新的打印窗口并写入数据
        newWindow.document.write('<html><head><title>打印</title></head><body>');
        newWindow.document.write(printContentHTML); // 将格式化后的内容写入打印窗口
        newWindow.document.write('</body></html>');
        newWindow.document.close(); // 关闭文档写入
        newWindow.print(); // 执行打印操作
      },
      /** 统计按钮操作 **/
      handleStatistic() {
        // 显示统计对话框
        this.dialogVisible = true;

        // 调用后端接口获取统计数据
        listProgress(this.queryParams).then(response => {
          // 假设后端返回的数据包含 rows，contractName 和 amount 字段
          const projectId = response.rows.map(item => item.projectId);
          const progress = response.rows.map(item => item.progress);

          // 更新 chartData
          this.chartData = { projectId: projectId, progress: progress };

          // 渲染图表
          this.$nextTick(() => {
            this.renderChart(); // 渲染图表
          });
        }).catch(error => {
          console.error("获取进度数据失败", error);
        });
      },

      renderChart() {
        var myChart = echarts.init(document.getElementById('echart-container')); // 获取图表容器
        var option = {
          title: {
            text: '统计',
          },
          tooltip: {},
          legend: {
            data: ['进度'],
          },
          xAxis: {
            type: 'category',
            data: this.chartData.projectId,
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value} %',
            },
          },
          series: [
            {
              name: '进度',
              type: 'bar',
              data: this.chartData.progress,
              itemStyle: {
                color: function (params) {
                  // 根据进度不同设置颜色
                  var value = params.value;
                  if (value < 30) {
                    return '#5470c6';
                  } else if (value < 70) {
                    return '#5587de';
                  } else {
                    return '#589df7';
                  }
                }
              },
              barWidth: '30%', // 设置进度条宽度
              label: {
                show: true, // 显示数据标签
                position: 'top', // 标签位置
                formatter: '{c}%', // 标签内容显示百分比
                color: '#fff', // 标签字体颜色
              },
              animationDuration: 1000, // 动画时长
              animationEasing: 'cubicOut', // 动画效果
            },
          ],
        };
        myChart.setOption(option); // 设置图表的配置项和数据
      },

      /** 关闭对话框时的处理 */
      handleCloseDialog(done) {
        this.dialogVisible = false;
      },
    }
  };
</script>
